home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 896 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.4 KB

  1. Path: crl.crl.com!not-for-mail
  2. From: bobfry@crl.com (Robert Fry)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Alignment restrictions...
  5. Date: 9 Jan 1996 16:00:46 -0800
  6. Organization: CRL Dialup Internet Access
  7. Message-ID: <4cuvje$48l@crl.crl.com>
  8. References: <DKxHxG.EK1@ridgecrest.ca.us>
  9. NNTP-Posting-Host: crl.com
  10.  
  11. mcclung@owens.ridgecrest.ca.us (Scott McClung) writes:
  12.  
  13. >Hi,
  14.  
  15. >In architectures that have alignment restrictions on certain types (i.e.
  16. >ints aligned on 4 byte boundaries, etc.), does anyone have any clean
  17. >way of retrieving values that are not aligned correctly?
  18.  
  19. >I was porting some code out that had statements like:
  20.  
  21. >short value;  /* 16 bit value */
  22. >char *ptr;    /* 32 bit pointer, no alignment restrictions */
  23.  
  24. >value = *(short *)ptr;
  25.  
  26. >It worked on, say, Intel x86, or on values of ptr that happened to be
  27. >aligned (auto variables, in this case), but is not a general solution
  28. >on SPARC or other RISC architectures (MIPS and PA-RISC have similar
  29. >restrictions, if I recall.)  The pointer in question happened to be
  30. >into an mmap()'ed image file, so the alignment is not guaranteed.  Bus
  31. >errors.
  32.  
  33. The last time I ran across this one, good ol' memcpy() did the trick. 
  34. Since our compiler inlined the call, it even generated code that was 
  35. exactly as fast as I could do in hand-coded assembly.
  36.  
  37. e.g:
  38. memcpy(value, ptr, sizeof( value)); /* with appropriate casts, as needed. */
  39.  
  40. What do others use?
  41.  
  42.